import pandas as pd
import numpy as np

# dpath = 'data/dxy22.csv'      # 这个的列名是编码
dpath = 'data/dxy3.csv'         # 列名为中文名
df_0 = pd.read_csv(dpath)
df = df_0
df.head()

from sklearn.model_selection import train_test_split

# 1.加载数据            # mp.close()
target_col = 3      # 目标建模列, 倒数三列依次为["电流", "功率", "电压"], 对应target_col的值为[3, 2, 1].
X = np.array(df.iloc[:, :-3])
Y = np.array(df.iloc[:, -target_col])

# 2.拆分测试集、训练集。
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=0)

from sklearn import linear_model

# 标准化, 比较复杂
# scale = False
scale = False
if scale:
    from sklearn import preprocessing
    std = preprocessing.StandardScaler()
    X_train = std.fit_transform(X_train)
    X_test = std.fit_transform(X_test)
    model = linear_model.LinearRegression()
    model.fit(X_train, Y_train)
    y_pre2 = model.predict(X_test)
    from sklearn.metrics import mean_squared_error
    print('--- 标准化的均方误差2: ', mean_squared_error(y_pre2, Y_test))

model = linear_model.LinearRegression()
model.fit(X_train, Y_train)
print('系数: ', model.coef_)  #线性模型的系数
print('截距: ', model.intercept_)  #截距

ff = 'y = '
for i in range(X.shape[1]):
    coef = round(model.coef_[i], 3)
    # ff += f'({coef}) * x{i} + '
    xname = df.columns[i]
    ff += f'({coef}) * ({xname}) + '

    if i == X.shape[1]-1:
        ff += f'{round(model.intercept_, 3)}'
print('表达式为: ', ff)


# ---- 预测数据并验证模型精度
pred_y = model.predict(X_test)

# 输出模型的评估指标
y = Y_test
x = X_test

import sklearn.metrics as sm
print('平均绝对值误差：', sm.mean_absolute_error(y, pred_y))
print('平均平方误差：', sm.mean_squared_error(y, pred_y))
print('中位绝对值误差：', sm.median_absolute_error(y, pred_y))
print('R2得分：', sm.r2_score(y, pred_y))

# ---- 展示预测结果
import matplotlib.pyplot as mp
xx = np.linspace(start=1, stop=y.shape[0], num=y.shape[0],dtype=int)

nums = 60       # 展示数量

mp.figure("Linear Regression", facecolor='lightgray')
mp.title('Linear Regression', fontsize=16)
mp.grid(linestyle=':')
mp.xlabel('x')
mp.ylabel('y')
mp.plot(xx[:nums], pred_y[:nums], c='green', label='predict_data')
mp.plot(xx[:nums], Y_test[:nums], c='yellow', label='real_data')
mp.legend()
mp.tight_layout()
mp.show()

# mp.close()